<template>
  <div class="scheduler-management">
    <el-card class="main-card" :body-style="{ padding: '20px' }">
      <h1 class="page-title">情报收集调度器管理</h1>

      <!-- 调度器状态区域 -->
      <el-card class="status-card" :body-style="{ padding: '15px' }">
        <h2 class="section-title">📊 调度器状态</h2>
        <div class="status-content">
          <div class="status-item">
            <span class="status-label">运行状态:</span>
            <el-tag
              :type="schedulerStatus.running ? 'success' : 'warning'"
              class="status-tag"
            >
              <span
                class="status-dot"
                :class="schedulerStatus.running ? 'running' : 'paused'"
                >●</span
              >
              {{ schedulerStatus.running ? "运行中" : "已暂停" }}
            </el-tag>
            <el-button
              v-if="schedulerStatus.running"
              type="warning"
              size="small"
              class="status-btn"
              :loading="actionLoading"
              @click="handlePause"
            >
              暂停
            </el-button>
            <el-button
              v-else
              type="success"
              size="small"
              class="status-btn"
              :loading="actionLoading"
              @click="handleResume"
            >
              恢复
            </el-button>
          </div>
          <div class="status-item">
            <span class="status-label">总任务数:</span>
            <span class="status-value">{{
              schedulerStatus.total_jobs || 0
            }}</span>
          </div>
          <div class="status-item">
            <span class="status-label">下次执行:</span>
            <span class="status-value">{{ nextExecutionTime || "暂无" }}</span>
          </div>
        </div>
      </el-card>

      <!-- 调度配置区域 -->
      <el-card class="config-card" :body-style="{ padding: '15px' }">
        <h2 class="section-title">⚙️ 调度配置</h2>

        <!-- 定期收集任务 -->
        <div class="task-config">
          <h3 class="task-title">【定期收集任务】</h3>
          <DynamicForm
            v-model="regularTaskForm"
            :form-config="regularTaskFormConfig"
            :gutter="16"
            label-width="100px"
            :show-buttons="false"
          />
          <div class="cron-desc">
            {{ getCronDescription(regularTaskForm.cronExpression) }}
          </div>
          <div class="next-exec">
            下次执行: {{ getNextExecutionTime("periodic") || "暂无" }}
          </div>
        </div>

        <!-- 每周补充收集 -->
        <div class="task-config">
          <h3 class="task-title">【每周补充收集】</h3>
          <DynamicForm
            v-model="weeklyTaskForm"
            :form-config="weeklyTaskFormConfig"
            :gutter="16"
            label-width="100px"
            :show-buttons="false"
          />
          <div class="cron-desc">
            {{ getCronDescription(weeklyTaskForm.cronExpression) }}
          </div>
          <div class="next-exec">
            下次执行: {{ getNextExecutionTime("weekly") || "暂无" }}
          </div>
        </div>

        <!-- 高级配置 -->
        <div class="advanced-config">
          <div class="advanced-header" @click="toggleAdvancedConfig">
            <h3 class="task-title">【高级配置】</h3>
            <el-icon class="expand-icon">
              <ArrowDown v-if="showAdvancedConfig" />
              <ArrowUp v-else />
            </el-icon>
            <span class="expand-text">{{
              showAdvancedConfig ? "收起" : "展开"
            }}</span>
          </div>

          <div v-if="showAdvancedConfig" class="advanced-content">
            <DynamicForm
              v-model="advancedForm"
              :form-config="advancedFormConfig"
              :gutter="16"
              label-width="100px"
              :show-buttons="false"
            />
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="config-actions">
          <el-button
            type="primary"
            :loading="loading"
            @click="handleSaveConfig"
          >
            保存配置
          </el-button>
          <el-button
            type="success"
            :loading="actionLoading"
            @click="handleExecuteNow"
          >
            立即执行
          </el-button>
        </div>
      </el-card>

      <!-- 执行历史区域 -->
      <el-card class="history-card" :body-style="{ padding: '15px' }">
        <h2 class="section-title">📜 执行历史</h2>
        <DynamicTable
          ref="tableRef"
          :data="historyData"
          :columns="historyColumns"
          :loading="loading"
          :pagination="pagination"
          border
          @size-change="handleSizeChange"
          @current-page-change="handlePageChange"
        />
      </el-card>

      <!-- 提示信息 -->
      <div class="tip-message">
        <el-icon class="tip-icon"><InfoFilled /></el-icon>
        <span>提示: 配置保存后会自动热重载,无需重启服务</span>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { ArrowDown, ArrowUp, InfoFilled } from "@element-plus/icons-vue";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import {
  getSchedulerStatus,
  getSchedulerConfig,
  updateSchedulerConfig,
  pauseScheduler,
  resumeScheduler,
  triggerSchedulerTask,
} from "../servers";

// 状态数据
const schedulerStatus = reactive({
  running: false,
  total_jobs: 0,
  jobs: [] as Array<{
    id: string;
    name: string;
    trigger: string;
    next_run_time: string;
    pending: boolean;
  }>,
});
const showAdvancedConfig = ref(false);
const loading = ref(false);
const actionLoading = ref(false);
const tableRef = ref<DynamicTableInstance>();

// 定期收集任务表单数据
const regularTaskForm = reactive({
  enabled: true,
  taskName: "定期情报收集",
  cronExpression: "0 */2 * * *",
});

// 每周补充收集表单数据
const weeklyTaskForm = reactive({
  enabled: true,
  taskName: "每周情报补充收集",
  cronExpression: "0 3 * * 0",
});

// 高级配置表单数据
const advancedForm = reactive({
  misfireThreshold: 1800,
  maxInstances: 1,
  mergeMisfiredTasks: true,
});

// 定期任务表单配置
const regularTaskFormConfig: FormItemConfig[] = [
  {
    key: "enabled",
    name: "启用状态",
    type: "checkbox",
    params: {
      checked: true,
      label: "启用",
    },
    col: { span: 24 },
  },
  {
    key: "taskName",
    name: "任务名称",
    type: "input",
    params: {
      placeholder: "输入任务名称",
    },
    col: { span: 24 },
  },
  {
    key: "cronExpression",
    name: "Cron表达式",
    type: "input",
    params: {
      placeholder: "输入Cron表达式",
      clearable: true,
    },
    col: { span: 24 },
  },
];

// 每周任务表单配置
const weeklyTaskFormConfig: FormItemConfig[] = [
  {
    key: "enabled",
    name: "启用状态",
    type: "checkbox",
    params: {
      checked: true,
      label: "启用",
    },
    col: { span: 24 },
  },
  {
    key: "taskName",
    name: "任务名称",
    type: "input",
    params: {
      placeholder: "输入任务名称",
    },
    col: { span: 24 },
  },
  {
    key: "cronExpression",
    name: "Cron表达式",
    type: "input",
    params: {
      placeholder: "输入Cron表达式",
      clearable: true,
    },
    col: { span: 24 },
  },
];

// 高级配置表单配置
const advancedFormConfig: FormItemConfig[] = [
  {
    key: "misfireThreshold",
    name: "任务错过宽限时间（秒）",
    type: "input",
    params: {
      type: "number",
      min: 0,
      placeholder: "单位：秒",
    },
    col: { span: 24 },
  },
  {
    key: "maxInstances",
    name: "最大任务实例数",
    type: "input",
    params: {
      type: "number",
      min: 1,
    },
    col: { span: 24 },
  },
  {
    key: "mergeMisfiredTasks",
    name: "合并错过任务",
    type: "checkbox",
    params: {
      checked: true,
      label: "是",
    },
    col: { span: 24 },
  },
];

// 执行历史表格配置
const historyColumns: TableColumn[] = [
  {
    label: "时间",
    prop: "time",
    minWidth: 160,
  },
  {
    label: "任务名",
    prop: "taskName",
    minWidth: 120,
  },
  {
    label: "状态",
    prop: "status",
    minWidth: 80,
    slot: "status",
  },
  {
    label: "收集数",
    prop: "count",
    minWidth: 80,
  },
  {
    label: "耗时",
    prop: "duration",
    minWidth: 80,
  },
];

// 执行历史数据
const historyData = ref([
  {
    time: "2025-11-06 14:00",
    taskName: "定期收集",
    status: "success",
    count: "156条",
    duration: "23s",
  },
  {
    time: "2025-11-06 12:00",
    taskName: "定期收集",
    status: "success",
    count: "142条",
    duration: "19s",
  },
  {
    time: "2025-11-03 03:00",
    taskName: "每周补充",
    status: "success",
    count: "523条",
    duration: "67s",
  },
]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 3,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 计算下次执行时间
const nextExecutionTime = computed(() => {
  if (schedulerStatus.jobs && schedulerStatus.jobs.length > 0) {
    // 找到最近的执行时间
    const times = schedulerStatus.jobs
      .map((job) => job.next_run_time)
      .filter((time) => time)
      .sort();
    return times[0] || "暂无";
  }
  return "暂无";
});

// 获取指定任务的下次执行时间
const getNextExecutionTime = (taskType: "periodic" | "weekly") => {
  const jobId =
    taskType === "periodic"
      ? "intelligence_periodic_collection"
      : "intelligence_weekly_collection";
  const job = schedulerStatus.jobs.find((j) => j.id === jobId);
  return job?.next_run_time || "暂无";
};

// 获取Cron表达式描述
const getCronDescription = (cron: string) => {
  // 简单的Cron表达式解析
  if (cron === "0 */2 * * *") {
    return "说明: 每2小时执行一次";
  } else if (cron === "0 3 * * 0") {
    return "说明: 每周日凌晨3点执行";
  } else if (cron.includes("*/")) {
    const parts = cron.split(" ");
    if (parts[0] === "0" && parts[1].startsWith("*/")) {
      const hours = parts[1].replace("*/", "");
      return `说明: 每${hours}小时执行一次`;
    }
  }
  return `说明: Cron表达式 ${cron}`;
};

// 切换高级配置显示状态
const toggleAdvancedConfig = () => {
  showAdvancedConfig.value = !showAdvancedConfig.value;
};

// 处理Cron表达式解释
const handleCronExplain = (expression: string) => {
  ElMessage.info(`Cron表达式解析: ${expression}`);
  // 实际应用中可以显示更详细的解析弹窗
};

// 获取调度器状态
const fetchSchedulerStatus = async () => {
  try {
    const { data } = await getSchedulerStatus();
    if (data) {
      schedulerStatus.running = data.running || false;
      schedulerStatus.total_jobs = data.total_jobs || 0;
      schedulerStatus.jobs = data.jobs || [];
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取调度器状态失败");
  }
};

// 获取调度器配置
const fetchSchedulerConfig = async () => {
  try {
    const { data } = await getSchedulerConfig();
    if (data?.current_config) {
      const config = data.current_config;

      // 更新定期任务配置
      regularTaskForm.enabled =
        config["intelligence.scheduler.periodic.enabled"] === "true";
      regularTaskForm.taskName =
        config["intelligence.scheduler.periodic.name"] || "定期情报收集";
      regularTaskForm.cronExpression =
        config["intelligence.scheduler.periodic.cron"] || "0 */2 * * *";

      // 更新每周任务配置
      weeklyTaskForm.enabled =
        config["intelligence.scheduler.weekly.enabled"] === "true";
      weeklyTaskForm.taskName =
        config["intelligence.scheduler.weekly.name"] || "每周情报补充收集";
      weeklyTaskForm.cronExpression =
        config["intelligence.scheduler.weekly.cron"] || "0 3 * * 0";

      // 更新高级配置
      advancedForm.misfireThreshold = parseInt(
        config["intelligence.scheduler.misfire_grace_time"] || "1800"
      );
      advancedForm.maxInstances = parseInt(
        config["intelligence.scheduler.max_instances"] || "1"
      );
      advancedForm.mergeMisfiredTasks =
        config["intelligence.scheduler.coalesce"] === "true";
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取调度器配置失败");
  }
};

// 暂停调度器
const handlePause = async () => {
  try {
    await ElMessageBox.confirm("确定要暂停调度器吗？", "提示", {
      type: "warning",
    });
    actionLoading.value = true;
    const { message } = await pauseScheduler();
    ElMessage.success(message || "调度器已暂停");
    await fetchSchedulerStatus();
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "暂停调度器失败");
    }
  } finally {
    actionLoading.value = false;
  }
};

// 恢复调度器
const handleResume = async () => {
  try {
    actionLoading.value = true;
    const { message } = await resumeScheduler();
    ElMessage.success(message || "调度器已恢复运行");
    await fetchSchedulerStatus();
  } catch (error: any) {
    ElMessage.error(error?.message || "恢复调度器失败");
  } finally {
    actionLoading.value = false;
  }
};

// 保存配置
const handleSaveConfig = async () => {
  try {
    loading.value = true;

    // 构建配置对象
    const config: Record<string, string> = {
      "intelligence.scheduler.periodic.enabled": regularTaskForm.enabled
        ? "true"
        : "false",
      "intelligence.scheduler.periodic.cron": regularTaskForm.cronExpression,
      "intelligence.scheduler.periodic.name": regularTaskForm.taskName,
      "intelligence.scheduler.weekly.enabled": weeklyTaskForm.enabled
        ? "true"
        : "false",
      "intelligence.scheduler.weekly.cron": weeklyTaskForm.cronExpression,
      "intelligence.scheduler.weekly.name": weeklyTaskForm.taskName,
      "intelligence.scheduler.misfire_grace_time":
        advancedForm.misfireThreshold.toString(),
      "intelligence.scheduler.max_instances":
        advancedForm.maxInstances.toString(),
      "intelligence.scheduler.coalesce": advancedForm.mergeMisfiredTasks
        ? "true"
        : "false",
    };

    const { message } = await updateSchedulerConfig({
      action: "update",
      config,
    });

    ElMessage.success(message || "配置保存成功，调度器已自动热重载");
    // 重新获取状态和配置
    await Promise.all([fetchSchedulerStatus(), fetchSchedulerConfig()]);
  } catch (error: any) {
    ElMessage.error(error?.message || "保存配置失败");
  } finally {
    loading.value = false;
  }
};

// 立即执行
const handleExecuteNow = async () => {
  try {
    await ElMessageBox.confirm("确定要立即执行情报收集任务吗？", "提示", {
      type: "info",
    });
    actionLoading.value = true;
    const { message } = await triggerSchedulerTask();
    ElMessage.success(message || "任务已开始执行");
    // 延迟后刷新状态
    setTimeout(() => {
      fetchSchedulerStatus();
    }, 2000);
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "执行任务失败");
    }
  } finally {
    actionLoading.value = false;
  }
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  // TODO: 实际应用中调用获取历史数据接口
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  // TODO: 实际应用中调用获取历史数据接口
};

// 组件挂载时初始化
onMounted(async () => {
  await Promise.all([fetchSchedulerStatus(), fetchSchedulerConfig()]);
});

// 暴露方法
defineExpose({
  refreshData: async () => {
    await Promise.all([fetchSchedulerStatus(), fetchSchedulerConfig()]);
  },
});
</script>

<style scoped lang="scss">
.scheduler-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .main-card {
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .page-title {
    font-size: 20px;
    font-weight: 600;
    margin: 0 0 20px 0;
    color: #333;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .status-card {
    margin-bottom: 20px;
    border-radius: 6px;
    border: 1px solid #f0f0f0;
  }

  .status-content {
    padding: 10px 0;
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
  }

  .status-item {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .status-label {
    color: #666;
    width: 80px;
  }

  .status-value {
    color: #333;
    font-weight: 500;
  }

  .status-tag {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  .status-dot {
    &.running {
      color: #52c41a;
    }
    &.paused {
      color: #faad14;
    }
  }

  .status-btn {
    margin-left: 10px;
  }

  .config-card {
    margin-bottom: 20px;
    border-radius: 6px;
    border: 1px solid #f0f0f0;
  }

  .task-config {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px dashed #eee;

    &:last-of-type {
      border-bottom: none;
      margin-bottom: 10px;
    }
  }

  .task-title {
    font-size: 14px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #555;
  }

  .cron-desc {
    margin: 5px 0 0 116px; /* 与表单label对齐 */
    color: #666;
    font-size: 13px;
  }

  .next-exec {
    margin: 5px 0 0 116px;
    color: #666;
    font-size: 13px;
  }

  .advanced-config {
    margin-bottom: 20px;
  }

  .advanced-header {
    display: flex;
    align-items: center;
    cursor: pointer;
    margin-bottom: 15px;
  }

  .expand-icon {
    margin-left: 8px;
    width: 16px;
    height: 16px;
  }

  .expand-text {
    font-size: 13px;
    color: #1890ff;
    margin-left: 5px;
  }

  .advanced-content {
    padding: 10px 0 10px 10px;
    border-left: 2px solid #eee;
  }

  .config-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 10px;
  }

  .history-card {
    margin-bottom: 20px;
    border-radius: 6px;
    border: 1px solid #f0f0f0;
  }

  .tip-message {
    padding: 10px 15px;
    background-color: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #52c41a;
    font-size: 14px;
  }

  .tip-icon {
    color: #52c41a;
  }
}

// 状态标签样式
::v-deep .status-success {
  background-color: #f6ffed;
  color: #52c41a;
  border-color: #b7eb8f;
}

::v-deep .status-failed {
  background-color: #fff2f0;
  color: #f5222d;
  border-color: #ffccc7;
}

::v-deep .dynamic-form-item {
  margin-bottom: 10px;
}
</style>
